package com.qf.springcloud.filter;

import com.netflix.discovery.converters.Auto;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author zjw
 * @description 动态路由过滤器
 * @date 2021/11/12 10:43
 */
@Component
public class DynamicRouteFilter  extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER + 2000;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Object run() throws ZuulException {
        //1. 获取request
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();

        //2. 获取客户端请求携带的route参数
        String route = request.getParameter("route");

        //3. 如果不为null，
        if(!StringUtils.isEmpty(route)) {
            //4. 将参数作为key查询Redis
            Map<Object, Object> map = stringRedisTemplate.opsForHash().entries(route);
            if(map != null && map.size() > 0){
                //5. 获取到serviceId，requestURI，设置到RequestContext中，指定路由规则
                requestContext.put(FilterConstants.SERVICE_ID_KEY,map.get("serviceId"));
                requestContext.put(FilterConstants.REQUEST_URI_KEY,map.get("requestURI"));
            }
        }
        return null;
    }
}
